package org.example.demo.view.webview;

import cn.hutool.core.util.RandomUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.saxsys.mvvmfx.FxmlView;
import javafx.application.Platform;
import javafx.concurrent.Worker;
import javafx.fxml.Initializable;
import javafx.scene.web.WebView;
import org.example.demo.entity.HtmlDataEntity;
import org.example.demo.view.form.FormValidateViewModel;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @Description 常用图表 - 柱状图，折线图，饼状图，进度条
 * @Author sunruiqi
 * @Date 2024/11/1 15:59
 **/
public class ChartsView implements FxmlView<FormValidateViewModel>, Initializable {

    public WebView lineChartsView;
    public WebView barChartsView;
    public WebView pieChartsView;
    public WebView doughnutChartsView;

    private volatile boolean running = true; // 控制线程的运行状态
    private Thread pollingThread; // 轮询线程

    public static ChartsView chartsView;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        chartsView = this;
        //必须嵌套加载webview
        lineChartsView.getEngine().load(getClass().getResource("/org/example/demo/html/line-chart.html").toString());
        lineChartsView.getEngine().getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            if (newState == Worker.State.SUCCEEDED) {
                //添加数据
                lineChartsView.getEngine().executeScript("setData("+ generateLineDataJson() +")");
                //加载柱状图
                barChartsView.getEngine().load(getClass().getResource("/org/example/demo/html/bar-chart.html").toString());
                barChartsView.getEngine().getLoadWorker().stateProperty().addListener((obs1, oldState1, newState1) -> {
                    if(newState1 == Worker.State.SUCCEEDED){
                        //添加数据
                        barChartsView.getEngine().executeScript("setData("+ generateBarDataJson() +")");
                        //加载饼图
                        pieChartsView.getEngine().load(getClass().getResource("/org/example/demo/html/pie-chart.html").toString());
                        pieChartsView.getEngine().getLoadWorker().stateProperty().addListener((obs2, oldState2, newState2) -> {
                            if (newState1 == Worker.State.SUCCEEDED) {
                                //添加数据
                                pieChartsView.getEngine().executeScript("setData("+ generatePieDataJson() +")");
                                //加载环形图
                                doughnutChartsView.getEngine().load(getClass().getResource("/org/example/demo/html/doughnut-chart.html").toString());
                                doughnutChartsView.getEngine().getLoadWorker().stateProperty().addListener((obs3, oldState3, newState3) -> {
                                    if (newState1 == Worker.State.SUCCEEDED) {
                                        //添加数据
                                        doughnutChartsView.getEngine().executeScript("setData("+ generatePieDataJson() +")");
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
        //启动轮询线程
        startWebViewPollingThreads();
    }

    //webview轮询线程启动函数
    private void startWebViewPollingThreads(){
        //每5s轮询一次 -- 模拟：随机生成数据以js方式赋给webview
        pollingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (running){
                    Platform.runLater(()->{
                        if(lineChartsView.getEngine().getLoadWorker().stateProperty().get().equals(Worker.State.SUCCEEDED)){
                            lineChartsView.getEngine().executeScript("setData("+ generateLineDataJson() +")");
                        }
                        if(barChartsView.getEngine().getLoadWorker().stateProperty().get().equals(Worker.State.SUCCEEDED)){
                            barChartsView.getEngine().executeScript("setData("+ generateBarDataJson() +")");
                        }
                        if(pieChartsView.getEngine().getLoadWorker().stateProperty().get().equals(Worker.State.SUCCEEDED)){
                            pieChartsView.getEngine().executeScript("setData("+ generatePieDataJson() +")");
                        }
                        if(doughnutChartsView.getEngine().getLoadWorker().stateProperty().get().equals(Worker.State.SUCCEEDED)){
                            doughnutChartsView.getEngine().executeScript("setData("+ generatePieDataJson() +")");
                        }
                    });
                    try {
                        Thread.sleep(5*1000);
                    } catch (InterruptedException e) {
                        // 检查中断状态
                        if (Thread.currentThread().isInterrupted()) {
                            // 执行清理工作
                            // ...
                            // 重新设置中断状态
                            Thread.currentThread().interrupt();
                        }
                        System.out.println("Thread interrupted while sleeping");
                    }
                }
            }
        });
        pollingThread.start();
    }

    // 停止轮询线程
    public void stopPollingThread() {
        running = false; // 设置为 false，停止线程
        if (pollingThread != null) {
            pollingThread.interrupt(); // 中断线程
        }
    }

    //生成饼图，环形图数据json
    private String generatePieDataJson(){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        // 创建数据
        List<HtmlDataEntity> dataList = new ArrayList<>();
        dataList.add(new HtmlDataEntity( RandomUtil.getRandom().nextInt(1000), "Search Engine"));
        dataList.add(new HtmlDataEntity( RandomUtil.getRandom().nextInt(1000), "Direct"));
        dataList.add(new HtmlDataEntity( RandomUtil.getRandom().nextInt(1000), "Email"));
        dataList.add(new HtmlDataEntity( RandomUtil.getRandom().nextInt(1000), "Union Ads"));
        dataList.add(new HtmlDataEntity( RandomUtil.getRandom().nextInt(1000), "Video Ads"));
        try {
            jsonString = objectMapper.writeValueAsString(dataList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    //生成折线图数据json
    private String generateLineDataJson(){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        // 创建数据
        List<Integer> dataList = new ArrayList<>();
        for(int i=0;i<7;i++){
            dataList.add(RandomUtil.getRandom().nextInt(1600));
        }
        try {
            jsonString = objectMapper.writeValueAsString(dataList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    //生成柱状图数据json
    private String generateBarDataJson(){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        // 创建数据
        List<Integer> dataList = new ArrayList<>();
        for(int i=0;i<7;i++){
            dataList.add(RandomUtil.getRandom().nextInt(200));
        }
        try {
            jsonString = objectMapper.writeValueAsString(dataList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

}
